﻿package com.sgcc.nfc.lock.presentation.home

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.sgcc.nfc.lock.core.network.NetworkResult
import com.sgcc.nfc.lock.domain.model.DashboardStats
import com.sgcc.nfc.lock.domain.model.Warning
import com.sgcc.nfc.lock.domain.usecase.GetDashboardStatsUseCase
import com.sgcc.nfc.lock.domain.usecase.GetWarningsUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.launch

@HiltViewModel
class HomeViewModel @Inject constructor(
    private val getDashboardStatsUseCase: GetDashboardStatsUseCase,
    private val getWarningsUseCase: GetWarningsUseCase
) : ViewModel() {

    private val _stats = MutableLiveData<DashboardStats?>()
    val stats: LiveData<DashboardStats?> = _stats

    private val _warnings = MutableLiveData<List<Warning>>(emptyList())
    val warnings: LiveData<List<Warning>> = _warnings

    private val _isLoading = MutableLiveData(false)
    val isLoading: LiveData<Boolean> = _isLoading

    private val _error = MutableLiveData<String?>()
    val error: LiveData<String?> = _error

    init {
        refresh()
    }

    fun refresh() {
        viewModelScope.launch {
            _isLoading.value = true
            loadDashboard()
            loadWarnings()
            _isLoading.value = false
        }
    }

    private suspend fun loadDashboard() {
        when (val result = getDashboardStatsUseCase()) {
            is NetworkResult.Success -> _stats.value = result.data
            is NetworkResult.Error -> _error.value = result.message
            NetworkResult.Loading -> _isLoading.value = true
        }
    }

    private suspend fun loadWarnings() {
        when (val result = getWarningsUseCase(page = 1, pageSize = 5, status = 0)) {
            is NetworkResult.Success -> _warnings.value = result.data.data
            is NetworkResult.Error -> _error.value = result.message
            NetworkResult.Loading -> _isLoading.value = true
        }
    }
}
